<template>
    <div id="webcam-container" class="body-container" style="position:relative;">
        <video id="video" width="190" height="200" autoplay muted ></video>
    </div>
</template>

<script>
    import * as faceapi from 'face-api.js'
    export default {
        name: "Webcam",
        data() {
          return {
              loading: true
          }
        },
        mounted() {
            const video = document.getElementById('video');

            Promise.all([
                faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
                faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
                faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
                faceapi.nets.faceExpressionNet.loadFromUri('/models')
            ]).then(startVideo);

            function startVideo() {
                navigator.getUserMedia(
                    { video: {} },
                    stream => video.srcObject = stream,
                    err => console.error(err)
                )
            }

            video.addEventListener('play', () => {
                const canvas = faceapi.createCanvasFromMedia(video);
                canvas.setAttribute('id','canvas-webcam');
                canvas.style.position='absolute';
                document.getElementById('webcam-container').append(canvas);
                const displaySize = { width: video.width, height: video.height };
                faceapi.matchDimensions(canvas, displaySize);
                setInterval(async () => {
                    const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions()
                    const resizedDetections = faceapi.resizeResults(detections, displaySize);
                    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
                    faceapi.draw.drawDetections(canvas, resizedDetections);
                }, 100);

            });
        }
    }
</script>

<style scoped>

    .body-container {
        margin: 0;
        padding: 0;
        width: 100vw;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }

</style>